(function($, window, document, undefined) {

	var pluginName = 'OnChat', defaults = {
		'timeRoload': 10, // 10 seconds
		'pathImage' : '/public/images/logo-admin-neg.png',
	    'api'       : 'http://onchat.co/'
	}, _version = '1.0';

	function Plugin(element, options) {

		this.element = element;
		this.options = $.extend({}, defaults, options || {});
		this._name = pluginName;
		this._defaults = defaults, this._version = _version;
		this.init();

	}
	;
	

	Plugin.prototype = {
		instanceConversations : true,
		init : function() {
			var self = this;
			$(this.element).off('click.OnchatStart').on('click.OnchatStart',function(e){
                      e.preventDefault();
                      self.openOnChat();

			});
           self.isOnChat();
			

		},
        renderOnChat:function(){
             var self = this, markup = '<div class="OnChat">'
					+ '<div class="onChatheader"><img src="'
					+ this.options.pathImage + '" height="25px"/><span onChatClose class="bt-close-chat pull-right fa fa-times"></span></div>'
					+ '<div class="onChatbody"></div>' 
					+ '</div>',

		      isOpenedChat = $('.OnChat').size();
		     if(isOpenedChat === 0){
               $('body').append(markup);	
               $('[onChatClose]').off('click.CloseChat').on('click.CloseChat',function(){ self.closeConversations();
               });
            }
            self.toggleOnChat();

			
             
        }, 
       openOnChat:function(){
              var self= this ,
                  $ajax =  self.getIsOpenChat();
                  $ajax.success(function(data){
                  	self.renderOnChat();
       	            //if not exists session
       	            if (data.error == true) {
                        if(data.type == 'chat_off'){
                            self.addInfoChat(data.message);
                        	return;
                        }
                        self.loginConversations();
                        
						return;
					  };

                  });
        },
        addInfoChat:function(message){
        	$('.onChatbody').html('<span class="infoOnChat">'+message+'</span>');
        },
		toggleOnChat:function(){

			$('.OnChat').slideToggle(); 
		},
		getIsOpenChat:function(){
						var self = this;

		return	$.ajax({
				url : self.options.api + 'chat/isOpenChat',
				type : "post",
				dataType : 'jsonp',
				jsonp : 'onChatCallback'
			});

		},
		isOnChat : function() {

			var self= this,$ajax = this.getIsOpenChat();

			  $ajax.success(function(data) {
					if (data.error == true) {
						return;
					}
					self.renderOnChat();
					
					var ob = data.conversations['0'];
					$(self.element).data('dataonchat', {
						'r_id' : ob.r_id,
						'u_id' : ob.u_id
					});
					self.addConversations();
				})
		},

		loginConversations : function() {

			var self = this, markup = '<div class="col-xs-12 form-group">'
					+ '<label>Nome</label>'
					+ '<input name="onChatNameInput" class="form-control" placehoder="Digite o seu nome" />'
					+ '</div>'
					+ '<div class="col-xs-12 form-group">'
					+ '<label>Email</label>'
					+ '<input name="onChatEmailInput" class="form-control" placehoder="Digite o seu nome" />'
					+ '</div>'
					+ '<span enterOnChat class="btn btn-onChat">Entrar</span>';
			$('.OnChat .onChatbody').html(markup);
			$('[enterOnChat]').off('click').on('click', function() {
				self.enterConversations();
			});
		},
		enterConversations : function() {

			var self = this,
			    pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
			    $email = $('[name="onChatEmailInput"]'),
			    $name  = $('[name="onChatNameInput"]'),
			    $data =  this.serialize({'e':$email.val(),'n':$name.val()});

			    $('.OnChat .has-error').removeClass('has-error');
                if(!pattern.test($email.val())  || $name.val() == ''){
                                
                                if(!pattern.test($email.val())){
                                             $email.parent().addClass('has-error');
                                }   

                                if($name.val() == '') {
                                	$name.parent().addClass('has-error');
                                }
                     
                          return;
                } 
                 

			$.ajax({
				url : self.options.api +'chat/enter/',
				type : "post",
				dataType : 'jsonp',
				data:{'posted':$data},
				jsonp : 'onChatCallback',
				success : function(data) {
					if (data.error == true) {
						return;
					}
					var ob = data.conversations['0'];
					$(self.element).data('dataonchat', {
						'r_id' : ob.r_id,
						'u_id' : ob.u_id
					});
					self.addConversations();
				}
			});

		},
		addConversations : function() {
			var self = this, markup = '<div class="onChatfooter">'
					+ '<div class="onChatWriter">'
					+ '<textarea name="onChatMessage"></textarea>' + '</div>'
					+ '<span sendOnChat class="btn btn-onChat">Enviar</span>'
					+ '</div>';
			$('.OnChat').append(markup);
			self.getConversations();
			$('[sendOnChat]').on('click', function() {
				self.sendMessage();
			});
		},

		closeConversations:function(){
                
               var isConversation = $('.onChatfooter').size();               
               if(isConversation > 0){
                       this.confirmClose();
               }else{
                  this.destroyOnChat();
               }
               
		},
		destroyOnChat:function(){
			$('.OnChat').fadeIn(function(){$(this).remove();}); 	
		},
        confirmClose:function(){
             
        	var self = this,markup = 
        	          '<div class="onBoxOptions " style="display:none;">'
					+ '<div class="boxOnChatClose">'
					+ '</div>'
                    + '<span oncloseChatYes class="btn btn-default  bt-onChatClosing yes"> SIM</span>'
                    + '<span oncloseChatNo class="btn btn-danger bt-onChatClosing no"> NÃO</span>'
					+ '</div>',
			is_size = $('.onBoxOptions').size();

			if(is_size === 0){
		          $('.OnChat').append(markup);
		          $('.onBoxOptions').fadeIn();
                  $('[oncloseChatYes]').on('click.ClosingYes',function(){
                        self.outConversations();
                  });
                  $('[oncloseChatNo]').on('click.ClosingNo',function(){
                  	  $('.onBoxOptions').fadeOut(function(){$(this).remove();});
                  });

			};


        }   
		,
        outConversations:function(){
               var self = this ,$data = $(this.element).data('dataonchat');

               $.ajax({

				url : self.options.api + 'chat/onClose/' + $data.r_id,
				dataType : 'jsonp',
				jsonp : 'onChatCallback',
				success : function(data) {
                            self.destroyOnChat();

					
				}
			});
        },
	  sendMessage : function() {
			var self = this,
                $objMessage = $('[name="onChatMessage"]'), 
			    $data = $(this.element).data('dataonchat'), $message = $objMessage.val(), data = {
				'message' : $message
			};
			$objMessage.removeClass('has-chat-error');
			 if($objMessage.val() == ''){
                $objMessage.addClass('has-chat-error');
			 	return;
			 }


			data = (this.serialize(data));
			$.ajax({

				url : self.options.api +'chat/send/' + $data.r_id + '/'
						+ $data.u_id,
				type : "post",
				data : {
					s : data
				},
				dataType : 'jsonp',
				jsonp : 'onChatCallback',
				success : function(data) {

					$('[name="onChatMessage"]').val('');
                      self.renderConversationsItens();
                       
				}
			});
		},

         renderConversationsItens:function(){
                var self = this, data = $(this.element).data('dataonchat');
		$.ajax({

			url : self.options.api + 'ping/' + data.r_id + '/' + data.u_id,
			dataType : 'jsonp',
			jsonp : 'onChatCallback',
			success : function(data) {
				if(data.error === true){
					$('.onChatbody').html(data.message);
					self.resetBoxOnChat();
				    self.instanceConversations = false;
					return;
				}
				self.addItem(data);
			},
			complete : function() {

			}
		});
  
         },

         resetBoxOnChat:function(){
         	$('.onChatfooter').remove();
         },
        initConversationsData:function(){
			 var self = this;
			 self.renderConversationsItens();
		    $time =  setTimeout(function() {
		    	if(self.instanceConversations){
			    self.initConversationsData();
			   }
		    }, (self.options.timeRoload * 1000));
            
			
		}
	         
		
		,
		getConversations : function() {
			var  $ul = '<ul class="onChatConversations">'
					+ '<ul>';
			$('.OnChat .onChatbody').html($ul);
			this.initConversationsData();
		},

		addItem : function(obj) {
			var itens = '';

			$.each(obj.conversations, function(i, item) {
				if(item.name !==  null && item.message !== null){
				itens += '<li class="' + item.type
						+ '"><span class="onchatname">' + item.name
						+ ' : </span><span class="onchattext">' + item.message
						+ '</span>'
                        + '<span class="timeOnChat"> '+(item.create !== null ? item.create : '' )+'</span>'  
						+'</li>';
					}
			});

			$('.onChatConversations').html(itens);
		},
		serialize : function(e) {
			var t, n, r, i = "", s = "", o = 0, u = function(e) {
				var t = 0, n = 0, r = e.length, i = "";
				for (n = 0; n < r; n++) {
					i = e.charCodeAt(n);
					if (i < 128) {
						t += 1
					} else if (i < 2048) {
						t += 2
					} else {
						t += 3
					}
				}
				return t
			};
			_getType = function(e) {
				var t, n, r, i, s = typeof e;
				if (s === "object" && !e) {
					return "null"
				}
				if (s === "object") {
					if (!e.constructor) {
						return "object"
					}
					r = e.constructor.toString();
					t = r.match(/(\w+)\(/);
					if (t) {
						r = t[1].toLowerCase()
					}
					i = [ "boolean", "number", "string", "array" ];
					for (n in i) {
						if (r == i[n]) {
							s = i[n];
							break
						}
					}
				}
				return s
			};
			type = _getType(e);
			switch (type) {
			case "function":
				t = "";
				break;
			case "boolean":
				t = "b:" + (e ? "1" : "0");
				break;
			case "number":
				t = (Math.round(e) == e ? "i" : "d") + ":" + e;
				break;
			case "string":
				t = "s:" + u(e) + ':"' + e + '"';
				break;
			case "array":
			case "object":
				t = "a";
				for (n in e) {
					if (e.hasOwnProperty(n)) {
						i = _getType(e[n]);
						if (i === "function") {
							continue
						}
						r = n.match(/^[0-9]+$/) ? parseInt(n, 10) : n;
						s += this.serialize(r) + this.serialize(e[n]);
						o++
					}
				}
				t += ":" + o + ":{" + s + "}";
				break;
			case "undefined":
			default:
				t = "N";
				break
			}
			if (type !== "object" && type !== "array") {
				t += ";"
			}
			return t;
		}

	};

	$.fn[pluginName] = function(options) {
		return this
				.each(function() {
					if (!$.data(this, 'plugin_' + pluginName)) {
						$.data(this, 'plugin_' + pluginName, new Plugin(this,
								options));
					}
				});
	};

})(jQuery, window, document);